/*新增费用*/
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	ScrollView, KeyboardAvoidingView, Platform, Image
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { Common } from '../../../../component/common/Common.js';
import { Button } from '../../../../components/form/button';
import { RadiusGroupCpt } from '../_components/RadiusGroupCpt'
import { orderBaseStyle } from '../_common/style.js'
import { FormItem } from '../../../../components/form/formItem'
import { CURRENCY } from '../../../../utils/helper';
import { AddressCpt } from '../_components/AddressCpt';
import ToastUtil from '../../../../utils/toast';
import Utils from '../../../../utils/utils';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';


const scale = GLOBAL.SCALE;

export class AdressPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '新增运输',
			headerTintColor: '#272727',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#272727' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			},
			headerStyle: {
				elevation: 0,
				backgroundColor: '#F5F5F5',
				borderBottomWidth: 0,
			},
		}
	};
	constructor(props) {
		super(props);
		let { initData, editData } = this.props.navigation.state.params || {};
		console.log('PayPage页面参数', this.props.navigation.state.params)

		this.state = {
			lostRateIndex: -1,
			lostRateVisible: false,
		}

		this.deliveryDataBuy = initData.deliveryDataBuy || [] //交货方式 - 采
		this.deliveryDataSell = initData.deliveryDataSell || [] //交货方式 -销
		this.transportTypeData = initData.transportTypeData || [] //运输方式
		this.lossData = initData.lossData || [];//运损承担方
		this.lostRateData = initData.lostRateData || [];//途损率
		this.lostRateDataOld = initData.lostRateData || [];//途损率



		this.editData = JSON.parse(JSON.stringify(editData)) || {}
		this.orderFlag = initData.orderFlag || {}

		// 涂损率文本特殊处理
		this.editData.sellData.lostRenderName = this.editData.sellData.lostRender == '2' ? '对方' : this.editData.sellData.lostRenderName || null
		this.editData.buyData.lostRenderName = this.editData.buyData.lostRender == '2' ? '对方' : this.editData.buyData.lostRenderName || null

		// 地址用 必填
		this.isVerify = {
			startAddress: null,
			endAddress: null
		}
	}

	componentWillMount () {
		let { buyData, sellData } = this.editData || {};
		//编辑
		if (sellData.deliveryType) {
			this._editFn();
		}
	}
	//
	_editFn = () => {
		// let { sellData } = this.editData || {};
		// let isLostRate = sellData.lostRateBig || sellData.lostRateBig == '0' ? true : false;
		// this.setState({
		// 	isLostRate: isLostRate
		// })
	}


	// 转采 - 交货方式
	_turn = (id) => {
		let lsObj = {};
		switch (id) {
			case 'S':
				lsObj.name = "我司自提";
				lsObj.key = "T";
				break;
			case 'T':
				lsObj.name = "客户自提";
				lsObj.key = "Q";
				break;
			case 'P':
				lsObj.name = "供应商配送";
				lsObj.key = "S";
				break;
			case 'U':
				lsObj.name = "货权转移";
				lsObj.key = "U";
				break;
		}
		return lsObj
	}

	// 单选
	_radiusItemFn = (itemData, id, indexKey, type) => {
		console.log('itemData-9999', itemData)
		let lsName = id + 'Name'
		// 交货方式
		if ('deliveryType' == id) {

			if (itemData == this.editData[type][id]) return

			this.editData[type][id] = itemData;
			this.editData[type][lsName] = this.deliveryDataSell[indexKey].dictName;
			//采购- 交货方式
			let objBuy = this._turn(itemData);
			this.editData.buyData[lsName] = objBuy.name;
			this.editData.buyData[id] = objBuy.key;

			this.editData.sellData.lostRateBig = null;
			this.editData.sellData.lostRate = null;
			this.editData.buyData.lostRateBig = null;
			this.editData.buyData.lostRate = null;

			//运承担
			this.editData.sellData.lostRender = null;
			this.editData.sellData.lostRenderName = null;
			this.editData.buyData.lostRender = null;
			this.editData.buyData.lostRenderName = null;

			this._clearFn(objBuy.key);
		}
		//运输方式
		if ('transportType' == id) {
			this.editData.sellData[lsName] = this.transportTypeData[indexKey].dictName;
			this.editData.sellData[id] = itemData;
			this.editData.buyData[lsName] = this.transportTypeData[indexKey].dictName;
			this.editData.buyData[id] = itemData;

			this.editData.sellData.lostRateBig = null;
			this.editData.sellData.lostRate = null;
			this.editData.buyData.lostRateBig = null;
			this.editData.buyData.lostRate = null;
		}
		//运损承担方
		if ('lostRender' == id) {
			this.editData.sellData[id] = itemData;
			this.editData.sellData[lsName] = this.lossData[indexKey].dictName;
			this.editData.buyData[id] = itemData;
			this.editData.buyData[lsName] = this.lossData[indexKey].dictName;
		}
		this.setState({
			ls: true
		})
	}

	// 清空 地址，运输方式，运输单价
	_clearFn = (type) => {
		// 清空地址
		//销
		this.editData.sellData.srcAddressId = null;
		this.editData.sellData.destAddressId = null;
		this.editData.sellData.srcAddress = null;
		this.editData.sellData.destAddress = null;
		//采
		this.editData.buyData.srcAddressId = null;
		this.editData.buyData.destAddressId = null;
		this.editData.buyData.srcAddress = null;
		this.editData.buyData.destAddress = null;

		//清空运输方式
		this.editData.buyData.transportType = null;
		this.editData.buyData.transportTypeName = '--';
		this.editData.sellData.transportType = null;
		this.editData.sellData.transportTypeName = null;

		// //运承担
		// this.editData.buyData.lostRender = null;
		// this.editData.sellData.lostRender = null;


		this.isVerify.startAddress = null;
		this.isVerify.endAddress = null;
		//清空运输方式
		//this.isVerify.trans = null;
		//清空运输单价
		this.setState({ ls: true })
	}

	//新增
	_addFn = () => {
		if (!this._verifyFn()) return;
		this.props.navigation.state.params && this.props.navigation.state.params.callBack(this.editData || null);
		this.props.navigation.goBack();
	}

	/* ------------------------- 地址 start------------------------ */

	//是否有运输方式
	_isTransport = (orderType) => {
		let result = false;
		let { deliveryType } = this.editData.sellData || {};
		if (orderType == 'S' && (deliveryType == 'S' || deliveryType == 'P')) { //销售
			result = true;
		}
		return result
	}

	//是否有 运承担 途损 运费成本
	_isFreight = (orderType) => {
		let result = false;
		let { deliveryType } = this.editData.sellData || {};
		if (orderType == 'S' && (deliveryType == 'S' || deliveryType == 'P')) { //销售
			result = true;
		}
		return result
	}

	// 地址/运输方式/运输单价 dome
	_addressView = () => {
		let { deliveryType, lostRender } = this.editData.sellData || {};
		return (
			<View>
				{
					deliveryType && deliveryType != 'P' ? this._renderAddressSelect({ title: '出库地', id: 'srcAddressId', value: this.editData.sellData.srcAddress || null, info: deliveryType == 'S' ? '落采合同' : '落采、销合同' }) : null
				}
				{
					(deliveryType == 'P' || deliveryType == 'S') ? this._renderAddressSelect({ title: '目的地', id: 'destAddressId', value: this.editData.sellData.destAddress || null, info: deliveryType == 'S' ? '落销合同' : '落采、销合同' }) : null
				}
				{/* 运损承担 */}
				{this._isFreight('S') && <RadiusGroupCpt data={{
					title: '运损承担',
					required: true,
					listData: this.lossData,
					selectedKey: lostRender,
					_radiusItemFn: this._radiusItemFn,
					id: 'lostRender',
					type: 'sellData'
				}} />}
				{this._isFreight('S') && this._lostRateFn()}
				{this._yfcb()}
			</View>
		)
	}

	_lostRateFn = () => {
		let { lostRateIndex } = this.state;
		let { contractStandard, lostRateBig } = this.editData.sellData;
		let arrowImg = require('../../../../imgs/arrowBlue.png');
		let timeStamp = new Date().getTime();
		return (
			<View style={{ paddingRight: 15 * scale }}>
				<TouchableOpacity style={orderBaseStyle.lostRate} onPress={() => { this._beforeModalOpen() }}>
					<Image source={arrowImg} style={{ transform: [{ 'rotate': '90deg' }], height: 12 * scale }} />
					<Text style={orderBaseStyle.standard}>{contractStandard == 0 ? '非标' : '标准'}</Text>
				</TouchableOpacity>
				<FormItem key={timeStamp} sizeType={'small'} editable={contractStandard == 0} keyboardType={'numeric'} handleCallBack={this._lostRate} required={true} placeHolder={'请输入'} label={'途损率'} value={lostRateBig} rightText={'千分之'} type={'input'} />
			</View>
		)
	}

	//判断是不是液体商品
	_isLiquidGoods = () => {
		let { initData } = this.props.navigation.state.params || {};
		let { goodsData } = initData || {};
		if (goodsData && goodsData.length && (goodsData[0].goodsState == "FLUID" || goodsData[0].goodsState == "GAS")) {
			return true;
		}
		return false;
	}

	//判断是不是要控制途损率
	_islost = () => {
		let { deliveryType } = this.editData.sellData || {};
		let reset = false;
		if (deliveryType == 'P' || deliveryType == 'S') {
			reset = true;
		}

		return reset;
	}


	// 商品液体 涂损率 
	_lostRateData = async () => {
		let { initData } = this.props.navigation.state.params || {};
		let { goodsData } = initData || {};
		let { deliveryType, transportType } = this.editData.sellData || {};
		let resultData = await HTTP.POST(API_GENERATE(API.NEW_ORDER_LOSTRATE), { goodsId: goodsData[0].goodsId, orderType: 'S', deliveryType, transportType })
		return resultData || [];
	}

	_beforeModalOpen = async () => {
		let { deliveryType, transportType } = this.editData.sellData || {};
		// 液体商品
		if (this._isLiquidGoods()) {
			if (!deliveryType) {
				ToastUtil.showWarning("请先选择交货方式");
				return false;
			} else if (!transportType) {
				ToastUtil.showWarning("请先选择运输方式");
				return false;
			}
			if (this._islost()) {
				this.lostRateData = await this._lostRateData();
			} else {
				this.lostRateData = this.lostRateDataOld;
			}
		} else {
			this.lostRateData = this.lostRateDataOld;
		}


		this.setState({
			lostRateVisible: true
		})
	}

	_closeModal = () => {
		this.setState({
			lostRateVisible: false
		})
	}

	//contractStandard 0非标  1标准
	_lostRateCallBack = (index) => {
		if (index == 0) {
			this.editData.sellData.lostRateBig = '';
			this.editData.sellData.contractStandard = 0;

			this.editData.buyData.lostRateBig = '';
			this.editData.buyData.contractStandard = 0;
		} else {
			this.editData.sellData.lostRateBig = this.lostRateData[index].dictName
			this.editData.sellData.contractStandard = 1;

			this.editData.buyData.lostRateBig = this.lostRateData[index].dictName
			this.editData.buyData.contractStandard = 1;
		}
		this.setState({
			lostRateIndex: index,
		}, () => {
			this._closeModal()
		})
	}

	//途损率
	_lostRate = (str) => {
		this.editData.sellData.lostRateBig = str;
		this.editData.buyData.lostRateBig = str;
	}





	// 渲染地址封装
	_renderAddressSelect = (addressParams) => {
		let { orderType, tCode } = this.orderFlag;
		let { deliveryType, companyId, companyName } = this.editData.sellData || {};
		let { title, id, info, value } = addressParams;
		if (id == 'srcAddressId') {
			this.isVerify.startAddress = true;
		} else {
			this.isVerify.endAddress = true;
		}
		return (
			<AddressCpt data={{
				id, title, info, value,
				navigation: this.props.navigation,
				paramsData: {
					tCode, orderType, companyId, deliveryType, /* agencyCompanyId ,agencyCompanyName, */
					companyName,
					companyIdBuy: this.editData.buyData.companyId || null,
					companyNameBuy: this.editData.buyData.companyName || null,
				},
				addressCallback: this._addressCallback,
			}} />
		)
	}

	// 地址回调函数
	_addressCallback = (addressParams) => {
		let lsName = addressParams.id == 'srcAddressId' ? 'srcAddress' : 'destAddress';
		this.editData.sellData[addressParams.id] = addressParams.addrId;
		this.editData.sellData[lsName] = addressParams.value;
		this.editData.buyData[addressParams.id] = addressParams.addrId;
		this.editData.buyData[lsName] = addressParams.value;
		this.setState({ ls: true })
	}

	// 验证
	_verifyFn = () => {

		console.log('this.editData', this.editData)

		let { buyData, sellData } = this.editData || {};
		let { deliveryType, lostRender, lostRateBig,
			srcAddressId, destAddressId, transportType, logisticsFee } = sellData;

		//交货方式-验证
		if (!deliveryType) {
			ToastUtil.showWarning('请先选择交货方式');
			return false;
		}
		//交货地验证
		if (this.isVerify.startAddress && !srcAddressId) {
			ToastUtil.showWarning('请先选择出库地');
			return false;
		}
		if (this.isVerify.endAddress && !destAddressId) {
			ToastUtil.showWarning('请先选择目的地');
			return false;
		}
		//运输方式
		if (this._isTransport('S') && !transportType) {
			ToastUtil.showWarning('请先选择运输方式');
			return false;
		}

		if (this._isFreight('S')) {
			//运损承担方-验证
			if (!lostRender) {
				ToastUtil.showWarning('请先选择运损承担方');
				return false;
			}

			//途损率-验证
			if (!lostRateBig && lostRateBig !== 0 && lostRateBig !== '0') {
				ToastUtil.showWarning('请输入途损率');
				return false;
			}
		}

		//运费成本
		if (this._checkYfcb() && Utils.isEmpty(logisticsFee)) {
			ToastUtil.showWarning('请输入运费成本');
			return false;
		}

		return true;

	}

	_activeFn = () => {
		let { sellData } = this.editData || {};
		let { transportType } = sellData || {};
		let { tCode } = this.orderFlag;
		return (<RadiusGroupCpt data={{
			title: '运输方式',
			required: true,
			listData: this.transportTypeData,
			selectedKey: sellData.transportType,
			_radiusItemFn: this._radiusItemFn,
			id: 'transportType'
		}} />)
	}

	//校验用 运费成本   (涉及我司自提(T)，我司配送(S)的，运费成本必填)
	_checkYfcb = () => {
		let result = false;
		let { sellData } = this.editData || {};
		let { deliveryType } = sellData;
		if (deliveryType == 'S' || deliveryType == 'P' || deliveryType == 'T') {
			result = true;
		}
		return result;
	}

	//运费成本
	_yfcb = () => {
		let { sellData } = this.editData || {};
		let { logisticsFee, currency, deliveryType } = sellData;
		if (this._checkYfcb()) {
			return <FormItem required={this._checkYfcb() ? true : false} keyboardType={'numeric'} handleCallBack={(text) => { this.editData.sellData.logisticsFee = text; }} placeHolder={'请输入'} label={'运费成本'} value={logisticsFee} rightText={CURRENCY.getUnit(currency).text + '/吨'} type={'input'} />
		}
		return null;
	}

	/* ------------------------- 地址 end------------------------ */

	render () {
		let { buyData, sellData } = this.editData || {};
		let { lostRateIndex, lostRateVisible } = this.state;
		let { deliveryType } = sellData || {};
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'} style={{
					paddingLeft: 12 * scale,
					paddingRight: 12 * scale
				}}>
					<View style={styles.body}>

						<View style={styles.borderWrapBox}>
							<Text style={styles.borderTips}>采购</Text>
							<View style={[styles.borderWrap]}>
								<FormItem labelStyle={styles.labelStyleActive} inputStyle={{ textAlign: 'left' }} sizeType={'small'} editable={false} required={true} label={'交货方式'} value={buyData.deliveryTypeName || '--'} type={'input'} />
								<FormItem labelStyle={styles.labelStyleActive} inputStyle={{ textAlign: 'left' }} sizeType={'small'} editable={false} required={true} label={'运输方式'} value={buyData.transportTypeName || '--'} type={'input'} />
							</View>
						</View>

						<View style={styles.borderWrapBox}>
							<Text style={[styles.borderTips, { color: '#45780A' }]}>销售</Text>
							<View style={[styles.borderWrap, { borderColor: '#45780A' }]}>
								<RadiusGroupCpt data={{
									title: '交货方式',
									required: true,
									listData: this.deliveryDataSell,
									selectedKey: sellData.deliveryType,
									_radiusItemFn: this._radiusItemFn,
									textStyleBox: orderBaseStyle.textStyle,
									id: 'deliveryType',
									type: 'sellData'
								}} />


								{/* 运输方式 */}
								{
									this._isTransport('S') ? this._activeFn() : null
								}
							</View>
						</View>

						{this._addressView()}

					</View>
				</ScrollView>
				<View style={styles.btnWarp}>
					<Button text={'添加'} width={300} height={34} onPress={this._addFn} />
				</View>
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={lostRateIndex} title={'涂损率'} listData={this.lostRateData || []} selectCallBack={this._lostRateCallBack} />
				)} isVisible={lostRateVisible} closeCallballFn={this._closeModal} />

			</KeyboardAvoidingView>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5',
	},
	body: {
		flex: 1,
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 20 * scale
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	borderWrapBox: {
		position: 'relative',
	},
	borderWrap: {
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: '#F5A726',
		marginTop: 20 * scale,
		marginBottom: 2 * scale,
		borderRadius: 4 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	borderTips: {
		position: 'absolute',
		backgroundColor: '#fff',
		height: 18 * scale,
		width: 52 * scale,
		lineHeight: 18 * scale,
		textAlign: 'center',
		top: 12 * scale,
		left: 150 * scale,
		fontSize: 13 * scale,
		color: '#F5A726',
		zIndex: 1
	},
	row: {
		flexDirection: 'row',
	},
	labelColor: {
		fontSize: 14 * scale,
		paddingLeft: 10 * scale,
	},
	labelStyleActive: {
		fontSize: 14 * scale
	}
})
